package com.pet.framework.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;




public class CookieHelper {

    public static final String FIELD_NAME = "hua1000pass";
    public static final String KEY = "dfyfhqs9";
    
    public static CookieAccount getAccount(String cookie){
    	CookieAccount account = new CookieAccount();
    	if (cookie != null) {
    	    try{
        	    byte[] cookieBytes = ByteHelper.hex2byte(cookie);
                byte[] decodedBytes = decryptData(cookieBytes, KEY.getBytes());
            	String decodedString = new String(decodedBytes);
            	String[] parts = decodedString.split("@");
            	account.accountId = Integer.parseInt(parts[0]);
                account.shopId = Integer.parseInt(parts[1]);
                if (parts.length > 3) {
                	account.phoneNumber = parts[2];
                }
    	    }catch(Exception e){    		
    	    }
    	}
        return account;
    }
    
    public static String createCookie(CookieAccount account){
    	String cookie = null;
    	try{
        	String content = account.accountId + "@" + account.shopId + "@" + account.phoneNumber +"@" + (System.currentTimeMillis() / 1000);
        	byte[] contentBytes = content.getBytes();
        	byte[] keyBytes = KEY.getBytes();
            byte[] cookieBytes = encryptData(contentBytes, keyBytes);
            cookie = ByteHelper.byte2hex(cookieBytes);
    	}catch(Exception e){    		
    	    e.printStackTrace();
    	}
        return cookie;
    }   
    
   


    public static byte[] encryptData(byte[] input, byte[] key) throws Exception { 
        SecretKey deskey = new javax.crypto.spec.SecretKeySpec(key, ALGORITHM); 
        Cipher c1 = Cipher.getInstance(ALGORITHM); 
        c1.init(Cipher.ENCRYPT_MODE, deskey); 
        byte[] cipherByte = c1.doFinal(input);   
        return cipherByte;  
    } 
    
    public static byte[] decryptData(byte[] input, byte[] key) throws Exception { 
        SecretKey deskey = new javax.crypto.spec.SecretKeySpec(key, ALGORITHM); 
        Cipher c1 = Cipher.getInstance(ALGORITHM); 
        c1.init(Cipher.DECRYPT_MODE, deskey); 
        byte[] clearByte = c1.doFinal(input);   
        return clearByte; 
    } 
    
    public static final String ALGORITHM = "DES";
    
    
}
